package com.example.onlinetaxi.ui.activity.MainPage.OrderFragments;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.onlinetaxi.BaiDuMap.RoutePlan.RoutePlan;
import com.example.onlinetaxi.LocalStroage.LocalStorage;
import com.example.onlinetaxi.R;
import com.example.onlinetaxi.Thread.PassengerGetOrderStateThread;
import com.example.onlinetaxi.callback.OrderCallBack.GetOrderCallBack;
import com.example.onlinetaxi.callback.OrderCallBack.OrderCallBack;
import com.example.onlinetaxi.dto.OrderDto.OrderDTO;
import com.example.onlinetaxi.ui.activity.RouteInfoPage.RouteInfoActivity;
import com.example.onlinetaxi.ui.activity.DriverToStartPage.DriverToStartActivity;
import com.example.onlinetaxi.util.OKHttpUtil.HttpUrl;
import com.example.onlinetaxi.util.OKHttpUtil.OKHttpUtil;
import com.example.onlinetaxi.util.TimeUtil;
import com.example.onlinetaxi.view.Adapter.WaitingOrderAdapter;
import com.example.onlinetaxi.view.Dialog.MyDialog;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WaitingOrderFragment extends Fragment {

    private View rootView;
    // 无订单提醒
    private TextView empty;
    // 订单列表
    private List<OrderDTO> orderList = new ArrayList<>();
    // 重新获取订单
    private GetOrderCallBack getOrderCallBack;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_waiting_order, container, false);

        initView();

        initEvent();

        return rootView;
    }

    private void initView() {
        empty = rootView.findViewById(R.id.waiting_order_empty);

        if (orderList.size() != 0) {
            empty.setVisibility(View.INVISIBLE);
        }
    }

    private void initEvent() {
        // 初始化订单列表控件
        initRecyclerView();

        // 初始化空页面
        if (orderList.size() != 0) {
            empty.setVisibility(View.INVISIBLE);
        } else {
            empty.setVisibility(View.VISIBLE);
        }
        // 初始化线程(至少有订单才会初始化)
        if (orderList.size() == 1) {
            // 使用线程，向后台发送叫车请求，并等待接收数据
            PassengerGetOrderStateThread.finished = false;
            PassengerGetOrderStateThread.thread = new Thread(new PassengerGetOrderStateThread.GetOrderState(getActivity(), DriverToStartActivity.class));
            PassengerGetOrderStateThread.thread.start();
        }
    }

    private void initRecyclerView() {
        // 找到布局文件中的recyclerView
        RecyclerView recyclerView = rootView.findViewById(R.id.waiting_order_list);
        /*指定RecyclerView布局方式*/
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        /*指定为LinearLayout布局*/
        recyclerView.setLayoutManager(layoutManager);
        /*适配去管理滑动显示*/
        WaitingOrderAdapter adapter = new WaitingOrderAdapter(orderList);

        // 设置点击回调函数
        adapter.setOrderCallBack(new OrderCallBack() {
            @Override
            public void jump(OrderDTO order) {
                // 设置当前订单号
                LocalStorage.currentOrderId = order.getId().toString();

                // 设置绘图点
                RoutePlan.startMap.put("city", order.getStartCity());
                RoutePlan.startMap.put("place", order.getStartInfo());
                RoutePlan.endMap.put("city", order.getEndCity());
                RoutePlan.endMap.put("place", order.getEndInfo());

                // 跳转到订单对应的等待页面
                Intent intent = new Intent(getActivity(), RouteInfoActivity.class);
                // 传递参数（当前等待秒数）
                Bundle bundle = new Bundle();
                bundle.putString("intentType", "2");
                bundle.putString("waitTime", Long.toString(TimeUtil.getDateDifference(order.getCreateTime(), TimeUtil.TimeStampToDate(new Date().getTime()))));
                // 添加信息
                intent.putExtras(bundle);
                startActivity(intent);
            }

            @Override
            public void clickButton(OrderDTO order) {
                showDialog(order);
            }
        });

        // 设置适配器
        recyclerView.setAdapter(adapter);
    }

    private void showDialog(OrderDTO order) {
        View.OnClickListener onCancelClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 取消，不操作
            }
        };

        View.OnClickListener onConfirmClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 点击确认
                // 向后端发送取消订单请求
                cancelOrder(order.getId().toString());

                // 清除当前订单
                LocalStorage.currentOrderId = null;

                // 关闭获取状态
                PassengerGetOrderStateThread.finished = true;
                // 关闭线程
                PassengerGetOrderStateThread.thread = null;

                // 刷新界面
                refresh();

                Toast.makeText(getActivity(), "您已取消叫车!", Toast.LENGTH_SHORT).show();
            }
        };

        MyDialog.drawable = getContext().getDrawable(R.drawable.dialog_confirm_driver);

        // 显示提示框
        MyDialog.showInfoDialog(getActivity(), "您是否要取消当前订单？", "取消", onCancelClickListener, "确认", onConfirmClickListener);
    }

    private void refresh() {
        // 重新获取order列表
        getOrderCallBack.refreshOrder();

        // 刷新当前页面
        initEvent();
    }

    private void cancelOrder(String orderId) {
        // 传入订单
        Map<String, String> map = new HashMap<>();
        map.put("orderId", orderId);

        // 发送取消订单请求
        OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "order", "cancelOrder");
    }

    public void setOrderList(List<OrderDTO> orderList) {
        this.orderList = orderList;
    }

    public void setGetOrderCallBack(GetOrderCallBack getOrderCallBack) {
        this.getOrderCallBack = getOrderCallBack;
    }
}